<template>
  <el-upload ref="uploadRef" class="upload-demo" drag :accept="accept" action="#" :multiple="multiple" :limit="1"
    :show-file-list="false" :http-request="httpRequest">
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      将文件拖拽到此区域,或 <em>点击文件上传</em>
    </div>
  </el-upload>
</template>

<script setup lang="ts">
import {
  computed,
  ref
} from 'vue';

import { ElNotification } from 'element-plus';

import _axios from '@/api/request';
import {
  closeLoading,
  openLoading
} from '@/utils/element';

const emit = defineEmits(['goBack'])
const { action, multiple, data, accept } = defineProps({
  action: {
    type: String,
    default: '/hjw-choose/book/import'
  },
  multiple: {
    type: Boolean,
    default: false
  },
  data: {
    type: [Object, Function],
    default: {}
  },
  accept: {
    type: String,
    default: '.xlsx'
  }
})

const uploadRef = ref(null)

function httpRequest(row) {//发起请求
  openLoading()
  let formData = new FormData();
  Object.keys(data).forEach(item => {
    formData.append(item, data[item]);
  })
  formData.append("file", row.file);
  _axios({
    method: "post",
    url: action,
    data: formData
  })
    .then((res) => {
      closeLoading()
      if (res?.code == 1) {
        ElNotification({
          title: '导入失败',
          message: res?.msg,
          duration: 0,
        })
      } else {
        emit('goBack', res)
      }
      uploadRef.value.clearFiles()
    }).catch((error) => {
      closeLoading()
      uploadRef.value.clearFiles()
    })
}

</script>

<style lang="scss">
.el-upload-dragger {
  width: 340px;
}
</style>